/*本程序的功能是：
esp32-s3通过IIC协议采集智慧农业板块的温湿度和光强数据，通过发送AT指令使L610模块与云平台建立mqtt连接或tcp连接并传输实时数据到云平台
*/
#include <Arduino.h>
#include <string.h>

// #define MQTT  //使用mqtt协议
#define TCP    //使用tcp协议

#include "L610.cpp"
#include "E53_IA1.cpp"


HardwareSerial SerialL610(1);

void setup() {
  //初始化Serial和SerialL610
  Serial.begin(115200);
  SerialL610.begin(115200, SERIAL_8N1, PIN_L610_RX,PIN_L610_TX);

  // 开启与智慧农业板块相连的I2C引脚
  Wire.begin(I2C_SDA_PIN,I2C_SCL_PIN);
  sht30.begin(I2C_SDA_PIN,I2C_SCL_PIN);
  if (lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
    Serial.println(F("BH1750 Advanced begin"));
  } else {
    Serial.println(F("Error initialising BH1750"));
  }
  uint16_t stat = sht30.readStatus();
  Serial.print(stat, HEX);
  Serial.println();
  delay(300);

  L610_Attach(1);  //发送AT指令使L610联网
  #ifdef MQTT
    MqttConnect(deviceid,mqttusername,mqttpwd,clientid,mqttServer_ip,mqttServer_Port,"0","60");  //建立Mqtt连接
    delay(500);
    L610_MQTTSub(deviceid,serverpubtopic,0);  //订阅主题
  #endif
  #ifdef TCP
    TCPConnect(socket_id,server_ip,server_port,"TCP");  //建立TCP连接
    SendDataToTCPServer(socket_id,(char*)access_token);  //向云平台发送Access_Token进行鉴权绑定设备
  #endif
}

void loop() {
  //读取数据
  Data data = ReadData();
  //上报数据到云平台
  #ifdef MQTT  //如果建立MQTT连接，则使用MQTT形式的jsonpayload形式上报数据
  //将数据整理成json格式
  String jsonpayload = "[{\"";
  jsonpayload = jsonpayload + device1;
  jsonpayload = jsonpayload + "\":";
  jsonpayload = jsonpayload + (String)data.light;
  jsonpayload = jsonpayload + "},{\"";

  jsonpayload = jsonpayload + device2;
  jsonpayload = jsonpayload + "\":";
  jsonpayload = jsonpayload + (String)data.temp;
  jsonpayload = jsonpayload + "},{\"";

  jsonpayload = jsonpayload + device3;
  jsonpayload = jsonpayload + "\":";
  jsonpayload = jsonpayload + (String)data.hum;
  jsonpayload = jsonpayload + "}]";

    L610_MQTTPub(deviceid,transdatatopic,0,1,jsonpayload);
  #endif

  #ifdef TCP  //如果使用的是TCP连接，则使用tcp形式的payload形式上报数据
  String payload = "";
  payload = payload  + (String)data.light;
  payload = payload  + ",";
  payload = payload  + (String)data.temp;
  payload = payload  + ",";
  payload = payload  + (String)data.hum;
  SendDataToTCPServer(socket_id,payload);
  #endif

  delay(500);    //每0.5s读取一次数据
}
